<template>
    <div class="lottery-management-container">
        <el-card>
            <div slot="header" class="card-header">
                <h2>彩票管理系统</h2>
            </div>

            <!-- 操作区域 -->
            <div class="operation-area">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-select v-model="selectedLotteryType" placeholder="请选择彩票类型" @change="handleTypeChange">
                            <el-option v-for="type in lotteryTypes" :key="type.code" :label="type.name"
                                :value="type.code"></el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="18" class="button-group">
                        <el-button type="primary" @click="syancLotterHistory">同步记录</el-button>
                        <el-button type="primary" @click="showAddRecordDialog">添加记录</el-button>
                        <el-button type="warning" @click="refreshHistory">刷新数据</el-button>
                    </el-col>
                </el-row>
            </div>

            <!-- 历史记录表格 -->
            <div class="history-table">
                <el-table :data="filteredHistory" border style="width: 100%; margin-top: 20px;">
                    <el-table-column prop="drawNumber" label="期号" width="120" align="center" sortable></el-table-column>
                    <el-table-column prop="front" label="前区号码" align="center">
                        <template slot-scope="scope">
                            <span v-for="(num, index) in scope.row.front" :key="index"
                                class="number-tag front-number">{{ num }}</span>
                        </template>
                    </el-table-column>
                    <!-- 后区号码列 - 仅当有后区时显示 -->
                    <el-table-column prop="back" label="后区号码" align="center"
                        v-if="currentLotteryType && currentLotteryType.hasBack">
                        <template slot-scope="scope">
                            <span v-for="(num, index) in scope.row.back" :key="index" class="number-tag back-number">{{
                                num }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="firstPrizeCount" label="一等奖(注)" width="120" align="center"
                        sortable></el-table-column>
                    <el-table-column prop="secondPrizeCount" label="二等奖(注)" width="120" align="center"
                        sortable></el-table-column>
                    <el-table-column label="操作" width="180" align="center">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]"
                    :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total"></el-pagination>
            </div>
        </el-card>

        <!-- 添加/编辑记录对话框 -->
        <el-dialog :title="isEditMode ? '编辑彩票记录' : '添加彩票记录'" :visible.sync="addRecordDialogVisible" width="60%"
            :before-close="handleDialogClose">
            <el-form :model="formData" :rules="formRules" ref="recordForm" label-width="120px">
                <el-form-item label="彩票类型" prop="type">
                    <el-select v-model="formData.type" disabled>
                        <el-option v-for="type in lotteryTypes" :key="type.code" :label="type.name"
                            :value="type.code"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="期号" prop="drawNumber">
                    <el-col :span="24">
                        <el-input v-model.number="formData.drawNumber" placeholder="请输入期号"
                            :disabled="isEditMode"></el-input>
                    </el-col>
                </el-form-item>

                <el-form-item label="前区号码" prop="front" :error="frontNumberError">
                    <div class="number-input-group">
                        <el-input v-for="(num, index) in formData.front" :key="index"
                            v-model.number="formData.front[index]" placeholder="请输入号码" class="number-input"
                            @change="validateNumberRange('front', index)"></el-input>
                    </div>
                    <div class="number-range-hint">
                        提示：请输入{{ frontNumberRange.min }}-{{ frontNumberRange.max }}之间的整数，共{{ frontNumberCount }}个
                        <template v-if="!currentLotteryType.front.allowDuplicates">，且不能重复</template>
                        <template v-if="currentLotteryType.front.allowDuplicates">，允许重复</template>
                    </div>
                </el-form-item>

                <!-- 后区号码表单 - 仅当有后区时显示 -->
                <el-form-item label="后区号码" prop="back" :error="backNumberError"
                    v-if="currentLotteryType && currentLotteryType.hasBack">
                    <div class="number-input-group">
                        <el-input v-for="(num, index) in formData.back" :key="index"
                            v-model.number="formData.back[index]" placeholder="请输入号码" class="number-input"
                            @change="validateNumberRange('back', index)"></el-input>
                    </div>
                    <div class="number-range-hint">
                        提示：请输入{{ backNumberRange.min }}-{{ backNumberRange.max }}之间的整数，共{{ backNumberCount }}个
                        <template v-if="!currentLotteryType.back.allowDuplicates">，且不能重复</template>
                        <template v-if="currentLotteryType.back.allowDuplicates">，允许重复</template>
                    </div>
                </el-form-item>

                <el-form-item label="一等奖注数" prop="firstPrizeCount">
                    <el-input v-model.number="formData.firstPrizeCount" placeholder="请输入一等奖注数"></el-input>
                </el-form-item>

                <el-form-item label="二等奖注数" prop="secondPrizeCount">
                    <el-input v-model.number="formData.secondPrizeCount" placeholder="请输入二等奖注数"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="addRecordDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitRecordForm">
                    {{ isEditMode ? '更新' : '保存' }}
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    getLotteryHistory,
    generateUniqueDrawNumber,
    saveToHistory,
    initializeHistoryData,
    addRecord,
    getAllLotteryTypes,
    updateRecord,
    deleteRecord,
    syncLotteryResult
} from '@/api/lottery_manage';

export default {
    name: 'LotteryManagement',
    data() {
        return {
            // 彩票类型
            lotteryTypes: [],
            selectedLotteryType: '',
            currentLotteryType: null,  // 当前选中的彩种详情

            // 历史记录数据
            lotteryHistory: [],
            filteredHistory: [],

            // 分页信息
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0
            },

            // 表单数据
            formData: {
                type: '',
                drawNumber: null,
                front: [],
                back: [],
                firstPrizeCount: 0,
                secondPrizeCount: 0
            },

            // 表单规则
            formRules: {
                type: [
                    { required: true, message: '请选择彩票类型', trigger: 'change' }
                ],
                drawNumber: [
                    { required: true, message: '请输入期号', trigger: 'blur' },
                    { type: 'number', message: '期号必须为数字', trigger: 'blur' },
                    { validator: this.validatePositiveInteger, trigger: 'blur' }
                ],
                firstPrizeCount: [
                    { required: true, message: '请输入一等奖注数', trigger: 'blur' },
                    { type: 'number', message: '必须为数字', trigger: 'blur' },
                    { validator: this.validateNonNegativeInteger, trigger: 'blur' }
                ],
                secondPrizeCount: [
                    { required: true, message: '请输入二等奖注数', trigger: 'blur' },
                    { type: 'number', message: '必须为数字', trigger: 'blur' },
                    { validator: this.validateNonNegativeInteger, trigger: 'blur' }
                ]
            },

            // 对话框状态
            addRecordDialogVisible: false,
            isEditMode: false,
            currentEditingRecord: null,

            // 号码验证相关
            frontNumberError: '',
            backNumberError: '',
            frontNumberCount: 0,  // 前区号码数量，从彩种配置获取
            backNumberCount: 0,   // 后区号码数量，从彩种配置获取
            frontNumberRange: { min: 0, max: 0 },  // 前区号码范围
            backNumberRange: { min: 0, max: 0 },   // 后区号码范围

            // 加载动画实例
            loadingInstance: null
        };
    },
    async created() {
        await this.getLotteryType()
        // 页面加载时获取历史数据
        if (this.lotteryTypes.length > 0) {
            this.selectedLotteryType = this.lotteryTypes[0].code;
            this.handleTypeChange(); // 触发类型变化，加载对应的配置
            this.loadHistoryData();
        }
    },
    methods: {
        // 获取彩种
        async getLotteryType() {
            try {
                const result = await getAllLotteryTypes({
                    page: 1,
                    size: 100000
                });
                if (result.code === 20000) {
                    this.lotteryTypes = result.data || [];
                }
            } catch (error) {
                this.$message.error(`获取彩种失败: ${error.message || '未知错误'}`);
                console.error('获取彩种失败:', error);
            }
        },

        // 加载历史数据
        async loadHistoryData() {
            if (!this.selectedLotteryType) return;

            try {
                this.loadingInstance = this.$loading({ text: '加载数据中...' });
                const response = await getLotteryHistory({
                    type: this.selectedLotteryType,
                    page: this.pagination.currentPage,
                    size: this.pagination.pageSize
                });

                this.lotteryHistory = response.data || [];
                this.filteredHistory = [...this.lotteryHistory];
                this.pagination.total = response.total || this.lotteryHistory.length;
                this.loadingInstance.close();
            } catch (error) {
                if (this.loadingInstance) {
                    this.loadingInstance.close();
                }
                this.$message.error(`加载失败: ${error.message || '未知错误'}`);
                console.error('加载历史数据失败:', error);
            }
        },

        // 同步历史记录
        async syancLotterHistory(){
            let result = await syncLotteryResult()
            if(result.code == 20000){
                let {successCount , errorCount , skipCount} = result.data
                this.$message.success(`操作成功，成功${successCount}条，失败${errorCount},跳过${skipCount}`)
                this.loadHistoryData()
            }
        },

        // 刷新数据
        refreshHistory() {
            this.pagination.currentPage = 1;
            this.loadHistoryData();
        },

        // 处理彩票类型变化
        handleTypeChange() {
            // 找到当前选中的彩种详情
            this.currentLotteryType = this.lotteryTypes.find(type => type.code === this.selectedLotteryType) || null;

            // 根据选择的彩票类型设置号码规则
            this.setLotteryNumberRules();
            this.refreshHistory();
        },

        // 设置彩票号码规则 - 从彩种配置中获取
        setLotteryNumberRules() {
            // 重置为默认值
            this.frontNumberCount = 0;
            this.frontNumberRange = { min: 0, max: 0 };
            this.backNumberCount = 0;
            this.backNumberRange = { min: 0, max: 0 };

            if (!this.currentLotteryType) {
                return;
            }

            // 从当前选中的彩种中获取前区配置
            if (this.currentLotteryType.front) {
                this.frontNumberCount = this.currentLotteryType.front.count || 0;
                this.frontNumberRange = {
                    min: this.currentLotteryType.front.min || 0,
                    max: this.currentLotteryType.front.max || 0
                };
            }

            // 从当前选中的彩种中获取后区配置
            if (this.currentLotteryType.hasBack && this.currentLotteryType.back) {
                this.backNumberCount = this.currentLotteryType.back.count || 0;
                this.backNumberRange = {
                    min: this.currentLotteryType.back.min || 0,
                    max: this.currentLotteryType.back.max || 0
                };
            }
        },

        // 显示添加记录对话框
        showAddRecordDialog() {
            if (!this.currentLotteryType) {
                this.$message.warning('请先选择彩种类型');
                return;
            }

            this.isEditMode = false;
            this.currentEditingRecord = null;
            this.addRecordDialogVisible = true;

            // 根据当前彩种配置初始化表单数据，严格按照count数量生成输入框
            this.formData = {
                type: this.selectedLotteryType,
                drawNumber: null,
                front: Array(this.frontNumberCount).fill(null),
                back: this.currentLotteryType.hasBack && this.backNumberCount > 0
                    ? Array(this.backNumberCount).fill(null)
                    : [],
                firstPrizeCount: 0,
                secondPrizeCount: 0
            };

            // 重置表单验证
            this.$nextTick(() => {
                if (this.$refs.recordForm) {
                    this.$refs.recordForm.resetFields();
                }
                this.frontNumberError = '';
                this.backNumberError = '';
            });
        },

        // 处理编辑
        handleEdit(record) {
            this.isEditMode = true;
            this.currentEditingRecord = { ...record };
            this.addRecordDialogVisible = true;

            // 填充表单数据，确保号码数量与配置一致
            this.formData = {
                type: record.type,
                drawNumber: record.drawNumber,
                front: [...record.front],
                back: [...(record.back || [])],
                firstPrizeCount: record.firstPrizeCount || 0,
                secondPrizeCount: record.secondPrizeCount || 0
            };

            // 重置表单验证
            this.$nextTick(() => {
                if (this.$refs.recordForm) {
                    this.$refs.recordForm.clearValidate();
                }
                this.frontNumberError = '';
                this.backNumberError = '';
            });
        },

        // 处理删除
        handleDelete(record) {
            this.$confirm(`确定要删除期号为 ${record.drawNumber} 的记录吗?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    this.loadingInstance = this.$loading({ text: '删除中...' });
                    // 调用删除API
                    const response = await deleteRecord(record);

                    if (response.code === 20000) {
                        this.loadHistoryData()
                        this.$message.success('删除成功');
                    } else {
                        this.$message.error(response.msg || '删除失败');
                    }

                    this.loadingInstance.close();
                } catch (error) {
                    if (this.loadingInstance) {
                        this.loadingInstance.close();
                    }
                    this.$message.error(`删除失败: ${error.message || '未知错误'}`);
                    console.error('删除记录失败:', error);
                }
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },

        // 验证号码范围和数量
        validateNumberRange(type, index) {
            // 对于没有后区的彩种，不验证后区
            if (type === 'back' && (!this.currentLotteryType || !this.currentLotteryType.hasBack)) {
                return true;
            }

            const numbers = type === 'front' ? this.formData.front : this.formData.back;
            const range = type === 'front' ? this.frontNumberRange : this.backNumberRange;
            const count = type === 'front' ? this.frontNumberCount : this.backNumberCount;
            const allowDuplicates = type === 'front'
                ? (this.currentLotteryType.front?.allowDuplicates || false)
                : (this.currentLotteryType.back?.allowDuplicates || false);
            const errorField = type === 'front' ? 'frontNumberError' : 'backNumberError';

            // 重置错误信息
            this[errorField] = '';

            // 1. 验证号码数量是否完整
            const filledCount = numbers.filter(n => n !== null && n !== '' && !isNaN(n)).length;
            if (filledCount < count) {
                this[errorField] = `请填写完整的${type === 'front' ? '前区' : '后区'}号码，共需${count}个`;
                return false;
            }

            // 2. 验证当前号码是否在有效范围
            if (numbers[index] === null || numbers[index] === '' || isNaN(numbers[index])) {
                this[errorField] = `${type === 'front' ? '前区' : '后区'}号码不能为空`;
                return false;
            }

            if (!Number.isInteger(numbers[index]) || numbers[index] < range.min || numbers[index] > range.max) {
                this[errorField] = `${type === 'front' ? '前区' : '后区'}号码必须在${range.min}-${range.max}之间的整数`;
                return false;
            }

            // 3. 如果不允许重复，验证是否有重复号码
            if (!allowDuplicates) {
                const nonEmptyNumbers = numbers.filter(n => n !== null && n !== '' && !isNaN(n));
                const uniqueNumbers = [...new Set(nonEmptyNumbers)];
                if (uniqueNumbers.length !== nonEmptyNumbers.length) {
                    this[errorField] = `${type === 'front' ? '前区' : '后区'}号码不能重复`;
                    return false;
                }
            }

            return true;
        },

        // 验证所有号码（提交前调用）
        validateAllNumbers(type) {
            const numbers = type === 'front' ? this.formData.front : this.formData.back;
            const count = type === 'front' ? this.frontNumberCount : this.backNumberCount;

            // 验证数量是否正确
            if (numbers.length !== count) {
                return false;
            }

            // 验证每个号码
            for (let i = 0; i < numbers.length; i++) {
                if (!this.validateNumberRange(type, i)) {
                    return false;
                }
            }
            return true;
        },

        // 验证正整数
        validatePositiveInteger(rule, value, callback) {
            if (value === null || value === '') {
                callback();
                return;
            }

            if (!Number.isInteger(value) || value <= 0) {
                callback(new Error('必须是正整数'));
            } else {
                callback();
            }
        },

        // 验证非负整数
        validateNonNegativeInteger(rule, value, callback) {
            if (value === null || value === '') {
                callback();
                return;
            }

            if (!Number.isInteger(value) || value < 0) {
                callback(new Error('必须是非负整数'));
            } else {
                callback();
            }
        },

        // 重置表单数据
        resetFormData() {
            // 重置表单数据为初始状态
            this.formData = {
                type: this.selectedLotteryType,
                drawNumber: null,
                front: Array(this.frontNumberCount).fill(null),
                back: this.currentLotteryType.hasBack && this.backNumberCount > 0
                    ? Array(this.backNumberCount).fill(null)
                    : [],
                firstPrizeCount: 0,
                secondPrizeCount: 0
            };

            // 清除验证状态
            if (this.$refs.recordForm) {
                this.$refs.recordForm.resetFields();
            }
            this.frontNumberError = '';
            this.backNumberError = '';
        },

        // 提交表单
        async submitRecordForm() {
            // 先验证号码数量和范围
            let isFrontValid = this.validateAllNumbers('front');
            let isBackValid = true;

            // 只有当有后区时才验证后区号码
            if (this.currentLotteryType && this.currentLotteryType.hasBack && this.formData.back.length > 0) {
                isBackValid = this.validateAllNumbers('back');
            } else {
                // 没有后区时，强制设置back为空数组
                this.formData.back = [];
            }

            if (!isFrontValid || !isBackValid) {
                return;
            }

            // 验证表单其他字段
            this.$refs.recordForm.validate(async (valid) => {
                if (valid) {
                    try {
                        // 保存加载实例引用
                        this.loadingInstance = this.$loading({
                            text: this.isEditMode ? '更新中...' : '保存中...',
                            target: '.el-dialog'
                        });

                        // 准备提交的数据
                        const formDataToSubmit = {
                            type: this.formData.type,
                            front: this.formData.front.map(Number),
                            firstPrizeCount: this.formData.firstPrizeCount,
                            secondPrizeCount: this.formData.secondPrizeCount,
                            drawNumber: this.formData.drawNumber
                        };

                        // 对于不允许重复的彩种，提交前排序
                        if (!this.currentLotteryType.front.allowDuplicates) {
                            formDataToSubmit.front.sort((a, b) => a - b);
                        }

                        // 只有当有后区时才添加后区数据
                        if (this.currentLotteryType && this.currentLotteryType.hasBack) {
                            formDataToSubmit.back = this.formData.back.map(Number);
                            // 对于不允许重复的彩种，提交前排序
                            if (!this.currentLotteryType.back.allowDuplicates) {
                                formDataToSubmit.back.sort((a, b) => a - b);
                            }
                        }

                        let response;
                        if (this.isEditMode) {
                            // 编辑模式，调用更新接口
                            response = await updateRecord(formDataToSubmit);
                        } else {
                            // 新增模式，调用添加接口
                            response = await addRecord(formDataToSubmit);
                        }

                        // 无论成功与否，都关闭加载动画
                        if (this.loadingInstance) {
                            this.loadingInstance.close();
                        }

                        if (response.code === 20000 || response.code === 200) {
                            this.$message.success(this.isEditMode ? '更新成功' : '保存成功');
                            this.addRecordDialogVisible = false;
                            // 成功后清除表单数据
                            this.resetFormData();
                            this.loadHistoryData(); // 重新加载数据
                        } else {
                            this.$message.error(response.msg || '操作失败');
                        }
                    } catch (error) {
                        // 异常情况下确保关闭加载动画
                        if (this.loadingInstance) {
                            this.loadingInstance.close();
                        }
                        this.$message.error(`${this.isEditMode ? '更新' : '添加'}失败: ${error.message || '未知错误'}`);
                        console.error(`${this.isEditMode ? '更新' : '添加'}记录失败:`, error);
                    }
                }
            });
        },

        // 格式化日期
        formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return `${date.getFullYear()}-${this.padZero(date.getMonth() + 1)}-${this.padZero(date.getDate())} ${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}:${this.padZero(date.getSeconds())}`;
        },

        // 补零
        padZero(num) {
            return num < 10 ? `0${num}` : num;
        },

        // 处理分页大小变化
        handleSizeChange(val) {
            this.pagination.pageSize = val;
            this.pagination.currentPage = 1;
            this.loadHistoryData();
        },

        // 处理页码变化
        handleCurrentChange(val) {
            this.pagination.currentPage = val;
            this.loadHistoryData();
        },

        // 处理对话框关闭
        handleDialogClose() {
            this.addRecordDialogVisible = false;
            // 对话框关闭时确保关闭加载动画
            if (this.loadingInstance) {
                this.loadingInstance.close();
            }
            this.resetFormData();
        }
    },
    // 组件销毁时确保关闭所有加载动画
    beforeDestroy() {
        if (this.loadingInstance) {
            this.loadingInstance.close();
        }
    }
};
</script>

<style scoped>
.lottery-management-container {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.operation-area {
    margin-bottom: 20px;
}

.button-group {
    text-align: right;
}

.number-tag {
    display: inline-block;
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-radius: 50%;
    margin-right: 5px;
    color: #fff;
    font-size: 14px;
}

.front-number {
    background-color: #42b983;
}

.back-number {
    background-color: #2196f3;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}

.number-input-group {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.number-input {
    width: 60px;
}

.number-range-hint {
    margin-top: 5px;
    font-size: 12px;
    color: #606266;
}
</style>
